package com.liang.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liang.controller.Utils.Result;
import com.liang.pojo.Book;
import com.liang.sevice.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    public Result getAll(){
        return new Result(true,bookService.list());
    }

    @GetMapping("{name}")
    public Result getByName(@PathVariable String name){
        return new Result(true,bookService.getById(name));
    }

    @PostMapping
    public Result save(@RequestBody Book book){
        return new Result(true,bookService.save(book));
    }

    @DeleteMapping("{id}")
    public Result delete(@PathVariable  Integer id){
        return new Result (bookService.removeById(id),null);
    }

    @PutMapping
    public Result update(@RequestBody Book book){
        return new Result(true,bookService.updateById(book));
    }

    @GetMapping("{currentPage}/{pageSize}")
    public Result getpage(@PathVariable Integer currentPage, @PathVariable Integer pageSize){

        IPage<Book> page = bookService.getpage(currentPage, pageSize);

        if(currentPage>page.getPages()){
            page=bookService.getpage((int) page.getPages(),pageSize);
        }

        return new Result(true,page);
    }


}
